import psutil
import time
import datetime
from datetime import datetime
import os
import telepot
from telepot.loop import MessageLoop
import sys

token = ''
TelegramBot = telepot.Bot(token)

control_value1 = ''
control_value2 = ''
alarm_value = 0.006

while True:
    currentHour = datetime.now().hour
    print(currentHour)
    if currentHour > 6 and currentHour < 9:
        with open("/home/max/multimedia/log.csv", "r") as file:
            last_line = file.readlines()[-1]
            fields = last_line.strip().split(",")
            control_value1 = fields[2]

        with open("/home/max/multimedia/log.csv", "r") as file:
            last_line = file.readlines()[-2]
            fields = last_line.strip().split(",")
            control_value2 = fields[2]

        print("last line = "+control_value1)
        print("pre last line = "+control_value2)

        if float(control_value1) > alarm_value and float(control_value2) > alarm_value:
            print("volume limit overcome")
            print("process checker")
            process_counter = 0
            for p in psutil.process_iter():
                if "chromium-browser" in p.name():
                    process_counter = process_counter + 1
            if process_counter >0:
                print("crhome already started")
            if process_counter == 0:
                print("run chrome!")
                os.system("mosquitto_pub -h  -u  -P  -m 'tv' -t 'pc/multimedia'")
                os.system("date>>/home/max/multimedia/runtime.log")
                os.system("echo "+control_value1+">>/home/max/multimedia/runtime.log")
                os.system("echo "+control_value2+">>/home/max/multimedia/runtime.log")
                TelegramBot.sendMessage('3072759','music started!')
    time.sleep(30)
